<template>
	<view v-if="userInfo.type == 1" class="page group-info">
		<watermark></watermark>
		<view v-if="!group.quit" class="group-members">
			<view class="member-items">
				<view v-for="(member,idx) in  groupMembers" :key="idx">
					<view class="member-item" v-if="idx<9">
						<head-image :isInfo="flagAdd(member)" :id="member.userId+''" :isShow="member.isAdmin" :item="member" :name="member.showNickName" :bid="member.userId" :type="1"
							:url="member.headImage" :isOwner="isOwner(member.userId)" :size="100" :online="member.online"></head-image>
						<view class="member-name">
							<text>{{member.showNickName}}</text>
						</view>
					</view>
				</view>
				<view class="invite-btn" @click="onInviteMember()">
					<uni-icons type="plusempty" size="28" color="#888888"></uni-icons>
				</view>
				<view class="invite-btn" @click="onShowMoreMmeber(0)">
					<view class="wxfont jian" color="#888888"></view>
				</view>
			</view>
			<view class="member-more" @click="onShowMoreMmeber(1)">{{`查看全部群成员${groupMembers.length}人`}} ></view>
		</view>
		<tool-list-wx :list="list3" @itemClick="itemClick3"></tool-list-wx>
		<view class="wxgroupInfo">
			<view class="xw-tool-list">
				<view class="xw-tool-list-content">
					<view class="xw-tool-item">
						<text class="xw-tool-text">消息免打扰</text>
						<switch color="#05C160" :checked="Baneddisturb" @change="switchChange($event, 'xxmdr')"
							style="transform:scale(0.75);" />
					</view>
				</view>
				<view class="xw-tool-list-content">
					<view class="xw-tool-item">
						<text class="xw-tool-text">置顶聊天</text>
						<switch color="#05C160" :checked="Banedtop" @change="switchChange($event, 'zdlt')"
							style="transform:scale(0.75);" />
					</view>
				</view>
				<view class="xw-tool-list-content">
					<view class="xw-tool-item">
						<text class="xw-tool-text">设置群成员可添加</text>
						<!-- group.tempAutoAdd == 'Y' ? true :false -->
						<u-switch  size="22" v-model="AutoAdd" activeColor="#f9ae3d" @change="settingAdd($event)"></u-switch>
					</view>
				</view>
				<!-- 只有群主和群管理员可以设置禁言 -->
				<view class="xw-tool-list-content">
					<view class="xw-tool-item">
						<text class="xw-tool-text">设置全体禁言</text>
						<u-switch  size="22" v-model="getProhibition" activeColor="#f9ae3d" @change="switchChange1($event)"></u-switch>
					</view>
				</view>
				<view class="xw-tool-list-content" >
					<view class="xw-tool-item" @click="goHistory">
						<text class="xw-tool-text" >历史聊天记录</text>
					</view>
				</view>
			</view>
			<view class="xw-tool-list">
				<view class="xw-tool-list-content" @click="qingchu">
					<view class="xw-tool-btn-item">
						<view class="xw-tool-btn-text" style="color: #FF5A5F;">清空群消息</view>
					</view>
				</view>
				<view class="xw-tool-list-content" @click="onQuitGroup">
					<view class="xw-tool-btn-item">
						<view class="xw-tool-btn-text" style="color: #FF5A5F;">删除并退出</view>
					</view>
				</view>
				<view class="xw-tool-list-content" v-if="isAdmin" >
					<view class="xw-tool-btn-item" @click="onDissolveGroup">
						<view class="xw-tool-btn-text" style="color: #FF5A5F;">解散该群</view>
					</view>
				</view>

			</view>
		</view>
	</view>
</template>

<script>
	import groupApi from '../../api/im/group'
	import groupMember from '../../api/im/groupMember.js'
	export default {
		data() {
			return {
				groupId: null, // 群组ID
				group: {}, // 群组信息
				groupMembers: [], // 群成员列表
				queryParams:{ // 查询参数
					pageNo: 1,
					pageSize: 10,
					groupId:''
				}
			}
		},
		methods: {
			// 判断是否有添加成员权限
			flagAdd(obj){
				let flag = false;
				// 群主或管理员有权限
				if(this.isAdmin || this.groupAdmin=='Y'){
					flag = true;
				}else{
					// 根据群设置判断是否允许添加
					flag = this.group.tempAutoAdd == 'Y' ? true : false;
				}
				// 自己总是有权限
				if(obj.userId == this.userStore.userInfo.id){
					flag = true;
				}
				return flag;
			},

			// 判断是否是群主
			isOwner(uid){
				return uid == this.group.ownerId ? true : false;
			},

			// 清空群聊天记录
			qingchu(){
				uni.showModal({
					title: "确认删除",
					content: `确认要删除与 '${this.group.name ? this.group.name : ''}'的好友记录吗?`,
					cancelText:'取消',
					confirmText:'确认',
					success: (res)=> {
						if (!res.cancel) {
							let msg = {
								id: this.groupId,
								type: 'GROUP',
							}
							this.chatStore.deleteMessageAll(msg);
							uni.showToast({
								title: "删除成功",
								icon: "none"
							})
						}
					}
				})
			},

			// 跳转到历史消息页面
			goHistory(){
				uni.navigateTo({
					url:'/pages/friend/personInfo/historyMSG?id='+this.groupId+'&type=GROUP'
				})
			},

			// 设置是否允许群成员添加
			settingAdd(flag){
				let formData = {
					id: this.groupId
				};
				// 检查权限
				if (this.groupAdmin=='N' && !this.isAdmin) {
					uni.showModal({
						title: '提示',
						content: '当前群聊仅群主和管理员可修改群聊名称',
						showCancel: false,
						confirmText: '我知道了',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击了"我知道了"按钮');
							}
						}
					});
					return;
				}
				// 调用API更新设置
				groupApi.updateAdd(formData).then(data=>{
					if(data){
						this.group.tempAutoAdd = flag?'Y':'N';
						data.forEach((msg) => {
							this.chatStore.removePrivateChat(msg.friendId);
						})
						this.groupStore.loadGroup();
						uni.showToast({
							title: "已设置",
							icon: 'none'
						});
					}
				})
			},

			// 设置群禁言状态
			switchChange1(flag){
				let formData = {
					id: this.groupId
				};
				// 检查权限
				if (this.groupAdmin=='N' && !this.isAdmin) {
					uni.showModal({
						title: '提示',
						content: '当前群聊仅群主和管理员可修改群聊名称',
						showCancel: false,
						confirmText: '我知道了',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击了"我知道了"按钮');
							}
						}
					});
					return;
				}
				// 调用API更新禁言状态
				groupApi.updateProhibitSpeak(formData).then(data=>{
					if(data){
						uni.showToast({
							title: "已设置",
							icon: 'none'
						});
						this.group.prohibition = flag?'Y':'N';
					}
				})
			},

			// 处理群设置开关变化
			switchChange(e, type){
				var yn = e.detail.value ? 'Y' : 'N';
				var formData = {
					groupId: this.groupId,
					userId: this.userInfo.id
				}, ynText;
				// 根据不同类型设置不同参数
				switch (type) {
					case 'xxmdr': // 消息免打扰
						formData.disturb = yn
						ynText = e.detail.value ? '已静默消息' : '已取消静默消息';
						break;
					case 'zdlt': // 置顶聊天
						formData.top = yn
						ynText = e.detail.value ? '已置顶' : '已取消置顶';
						break;
					case 'bcdtxl': // 保存到通讯录
						formData.keepGroup = yn
						ynText = e.detail.value ? '已保存' : '已移除';
						break;
					default:
						break;
				}
				// 更新成员信息
				groupMember.updateMemberInfo(JSON.stringify(formData)).then(data=>{
					if(data){
						uni.showToast({
							title: ynText,
							icon: 'none'
						});
					}
				})
			},

			// 处理群设置项点击
			itemClick3(e, i) {
				switch (i) {
					case 0: // 修改群名称
						if (this.groupAdmin=='N' && !this.isAdmin) {
							uni.showModal({
								title: '提示',
								content: '当前群聊只有群主和管理员可修改群聊名称',
								showCancel: false,
								confirmText: '我知道了'
							});
							return;
						}
						uni.navigateTo({
							url: 'editGroupName?id=' + this.group.id + '&name=' + this.group.name
						});
						break;
					case 1:
						
						break;
					case 2: // 查看群二维码
						uni.navigateTo({
							url: 'QRcode?groupId=' + this.group.id
						});
						break;
					case 3: // 编辑群公告
						if (this.groupAdmin=='N' && !this.isAdmin) {
							uni.showModal({
								title: '提示',
								content: '当前群聊只有群主和管理员可修改群聊名称',
								showCancel: false,
								confirmText: '我知道了'
							});
							return;
						}
						uni.navigateTo({
							url: 'editGroupNotice?id=' + this.group.id + '&notice=' + this.group.notice
						});
						break;
					case 4: // 设置群管理员
						if (!this.isAdmin) {
							uni.showModal({
								title: '提示',
								content: '当前群聊仅群主可添加管理员',
								showCancel: false,
								confirmText: '我知道了'
							});
							return;
						}
						uni.navigateTo({
							url: `/pages/group/group-member?id=${this.groupId}&type=2`
						})
						break;
					case 5: // 修改群内昵称
						let rename = this.group.remarkNickName ? this.group.remarkNickName : this.group.showNickName;
						uni.navigateTo({
							url: 'editGroupRemark?id=' + this.group.id + '&remarkNickName=' + rename
						});
						break;
					case 6: // 修改群备注名
						let name = this.group.remarkGroupName ? this.group.remarkGroupName : this.group.showGroupName;
						uni.navigateTo({
							url: 'editGroupAliasName?id=' + this.group.id + '&remarkGroupName=' + name
						});
						break;
					default:
						break;
				}
			},

			// 邀请新成员
			onInviteMember() {
				uni.navigateTo({
					url: `/pages/group/group-invite?id=${this.groupId}`
				})
			},

			// 查看更多成员
			onShowMoreMmeber(e) {
				if (this.groupAdmin=='N' && !this.isAdmin) {
					uni.showModal({
						title: '提示',
						content: '当前群聊仅群主和管理员可查看！',
						showCancel: false,
						confirmText: '我知道了'
					});
					return;
				}
				uni.navigateTo({
					url: `/pages/group/group-member?id=${this.groupId}&type=${e}`
				})
			},

			// 发送消息
			onSendMessage() {
				let chat = {
					type: 'GROUP',
					targetId: this.group.id,
					showName: this.group.remark,
					headImage: this.group.headImage,
				};
				this.chatStore.openChat(chat);
				uni.navigateTo({
					url: "/pages/chat/chat-box?chatIdx=0"
				})
			},

			// 退出群聊
			onQuitGroup() {
				uni.showModal({
					title: '确认退出?',
					content: `退出群聊后将不再接受群里的消息，确认退出吗?`,
					success: (res) => {
						if (res.cancel) return;
						groupApi.quitGroup(this.groupId).then(res => {
							uni.showModal({
								title: `退出成功`,
								content: `您已退出群聊'${this.group.name}'`,
								showCancel: false,
								success: () => {
									setTimeout(() => {
										uni.switchTab({
											url: "/pages/friend/index"
										});
										this.groupStore.removeGroup(this.groupId)
									}, 100)
								}
							})
						})
					}
				});
			},

			// 解散群聊
			onDissolveGroup() {
				uni.showModal({
					title: '确认解散?',
					content: `确认要解散群聊'${this.group.name}'吗?`,
					success: (res) => {
						if (res.cancel) return;
						groupApi.del(this.groupId).then(res => {
							uni.showModal({
								title: `解散成功`,
								content: `群聊'${this.group.name}'已解散`,
								showCancel: false,
								success: () => {
									setTimeout(() => {
										uni.switchTab({
											url: "/pages/friend/index"
										});
										this.groupStore.removeGroup(this.groupId)
									}, 100)
								}
							})
						})
					}
				});
			},

			// 加载群信息
			loadGroupInfo() {
				let params = {
					uid: this.userInfo.id,
					gid: this.groupId
				}
				this.groupStore.findGroups(params).then(data => {
					this.group = data;
					this.chatStore.updateChatFromGroup(data);
					this.groupStore.updateGroup(data);
				})
			},

			// 加载群成员列表
			loadGroupMembers() {
				uni.showLoading({
					title: '加载中'
				});
				this.queryParams.groupId = this.groupId;
				groupMember.getGroupMemberPage(this.queryParams).then(data=>{
					if (data.list.length>0) {
						this.groupMembers = data.list;
						// 查找所有成员
						this.$http({
							url: `/group/members/${this.groupId}`,
							method: "GET"
						}).then((members) => {
							if(members){
								let activeMembers = members.filter(m => !m.quit);
								this.groupStore.setMember(activeMembers);
								this.chatStore.updateMemberCount(this.groupId, activeMembers.length);
								
								// 更新本地群成员列表
								this.groupMembers = activeMembers;
							}
						})
					}
					uni.hideLoading();
				})
			}
		},
		computed: {
			// 获取群组信息
			groupInfo(){
				let groupList = this.groupStore.groups;
				groupList.forEach((item)=>{
					if(item.id == this.groupId){
						this.group = item;
						this.groupMembers = item.groupMembers;
						return item;
					}
				})
			},

			// 群设置列表
			list3() {
				this.groupInfo;
				let list = [{
					title: '群聊名称',
					path: '#',
					else: [{
						type: 'text',
						content: this.group.name ? this.group.name : ''
					}]
				},{
					title: '群主',
					path: '#',
					hideRight: true,
					else: [{
						type: 'text',
						content: this.ownerName ? this.ownerName : ''
					}]
				},{
					title: '群二维码',
					path: '#',
					else: [{
						type: 'img',
						content: '/static/wx/t05.png'
					}]
				},{
					title: '群公告',
					path: '#',
					else: [{
						type: 'text',
						content: this.group.notice ? this.group.notice : ''
					}]
				},{
					title: '设置群管理员',
					path: '#',
					else: [{
						type: 'text',
						content:''
					}]
				}];
				return list;
			},
			// 获取当前用户信息
			userInfo() {
				return this.userStore.userInfo;
			},
			// 判断是否是群管理员
			groupAdmin(){
				let item = this.groupMembers.find((m) => m.userId == this.userStore.userInfo.id);
				return item.isAdmin;
			},

			// 判断是否是群主
			isAdmin() {
				let users = this.userStore.userInfo;
				return users.id === this.group.ownerId ? true : false;
			},

			// 获取群主昵称
			ownerName() {
				let member = this.groupMembers.find((m) => m.userId == this.group.ownerId);
				return member && member.showNickName;
			},

			// 是否置顶聊天
			Banedtop() {
				return this.group.top == 'Y' ? true : false;
			},

			// 是否保存到通讯录
			BanedkeepGroup() {
				return this.group.keepGroup == 'Y' ? true : false;
			},

			// 是否消息免打扰
			Baneddisturb() {
				return this.group.disturb == 'Y' ? true : false;
			},

			// 是否全体禁言
			getProhibition() {
				return this.group.prohibition == 'Y' ? true : false;
			},

			// 是否允许自动加入
			AutoAdd(){
				return this.group.tempAutoAdd == 'Y' ? true : false;
			},
		},
		onLoad(options) {
			this.groupId = options.id; // 获取路由参数中的群组ID
		},
		mounted() {
			// 监听页面显示
			uni.$on('updateGroupMembers', () => {
				this.loadGroupMembers();
				this.loadGroupInfo();
			});
			this.loadGroupMembers();
		},
		beforeDestroy() {
			// 移除监听器
			uni.$off('updateGroupMembers');
		}
	}
</script>

<style lang="scss" scoped>
	.disabled-text {
	    color: gray; /* 文本颜色设为灰色，表示不可用 */
	}
	.disabled-text::after {
	    content: '（无权限）'; /* 添加提示文字 */
	    margin-left: 5px;
	    color: gray;
	}
	.group-info {
		.group-members {
			padding: 30rpx;
			background: white;

			.member-items {
				display: flex;
				flex-wrap: wrap;

				.member-item {
					width: 120rpx;
					display: flex;
					flex-direction: column;
					margin: 8rpx 2rpx;
					position: relative;
					align-items: center;
					padding-right: 5px;
					background-color: #fafafa;
					white-space: nowrap;

					.member-name {
						width: 100%;
						flex: 1;
						font-size: 14px;
						overflow: hidden;
						text-align: center;
						white-space: nowrap;
					}
				}

				.invite-btn {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 100rpx;
					height: 100rpx;
					margin: 10rpx;
					border: #686868 dashed 2px;
					border-radius: 10%;
				}
			}

			.member-more {
				padding: 20rpx;
				text-align: center;
				font-size: 16px;
			}
		}


		.group-detail {
			margin-top: 30rpx;
			padding: 30rpx;
			background: white;

			.detail-text {
				font-size: 28rpx;
				font-weight: 600;
			}

			.group-edit {
				padding: 20rpx;
				text-align: center;
				font-size: 30rpx;
			}
		}


		.btn-group {
			margin-top: 30rpx;
			padding: 30rpx;
			background: white;


			.btn {
				margin: 10rpx;
			}
		}
	}

	//新样式	
	/* #ifdef APP-PLUS */
	.bgColor {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: #ededed;
		overflow: auto;
	}

	/* #endif */
	/* #ifdef H5 */
	page {
		background: #ededed;
	}

	/* #endif */

	.xw-tool-list {
		display: flex;
		flex-direction: column;
		background-color: #ffffff;
		margin-bottom: 18rpx;
	}

	.xw-tool-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 26rpx 24rpx;
		border-bottom: 1px #eee solid;
	}

	.xw-tool-list-content:nth-last-child(1) .xw-tool-item {
		border: none;
	}

	.xw-tool-text {
		margin-right: auto;
	}

	.xw-tool-btn-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		padding: 20rpx 30rpx; //34rpx 44rpx
		border-bottom: 1px #eee solid;
		font-weight: bold;
		color: #5f698c;
	}

	.wxgroup-list {
		background-color: #fff;
		padding: 24rpx;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		margin-bottom: 24rpx;
	}

	.wxgroup-list-item {
		width: 20%;
		overflow: hidden;
		box-sizing: border-box;
		margin-top: 12rpx;
		margin-bottom: 12rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.wxgroup-list-icon .wxfont {
		color: #999;
		font-size: 46rpx;
	}

	.wxgroup-list-img {
		width: 105rpx;
		height: 105rpx;
		border-radius: 12rpx;
	}

	.wxgroup-list-icon {
		display: flex;
		flex-direction: column;
		width: 105rpx;
		height: 105rpx;
		border-radius: 12rpx;
		align-items: center;
		justify-content: center;
		border: 1px #ddd dashed;
	}

	.wxgroup-list-text {
		text-align: center;
		width: 105rpx;
		font-size: 24rpx;
		color: #999;
		margin-top: 12rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.xw-tool-else .text {
		color: #666;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		max-width: 520rpx;
	}
</style>